/*******************************************************************************
 * $Header$
 * $Revision$
 * $Date$
 *
 *==============================================================================
 *
 * Copyright©hxlife/hulife 
 * All rights reserved.
 * 
 * Created on 2018年5月7日
 *******************************************************************************/

package com.hualife.md.common.service.impl;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hualife.md.common.dao.mybatis.entity.DefKv;
import com.hualife.md.common.dao.mybatis.mapper.DefKvMapper;
import com.hualife.md.common.dto.wx.token.WeChatTokenResponseDTO;
import com.hualife.md.common.service.IWeChatGatewayService;
import com.hualife.support.exception.BusinessException;
import com.hualife.support.exception.SysException;
import com.hualife.support.util.EncoderUtil;
import com.hualife.support.util.HttpUtil;
import com.hualife.support.util.JsonUtil;
import com.hualife.support.util.RandomUtils;

/**
 * @description: TODO 此处填写 class 信息
 * @author 孙小冬 (mailto:sunxiaodong001@hualife.cc)
 */
@Service("weChatGatewayService")
public class WeChatGatewayServiceImpl implements IWeChatGatewayService {
	private static final Logger logger = LoggerFactory
			.getLogger(WeChatGatewayServiceImpl.class);

	@Autowired
	private DefKvMapper defKvMapper;

	String timestamp = String.valueOf(System.currentTimeMillis()); // 时间戳
	String nonce = RandomUtils.generateRandomCharAndNumber(32); // 32位随机字符串

	private static final String SOURCE = "ZSJPT";
	private static final String WEHCAT_QUERY_KEY = "qyh.key";
	private static final String WEHCAT_QUERY_TOKEN = "qyh.token"; // 获取Token
	private static final String TIMESTAMP = "timestamp";
	private static final String NONCE = "nonce";
	private static final String TRADE_SOURCE = "trade_source";
	private static final String SIGNATURE = "signature";
	private static final String SUCCESS = "suc";

	private Map<String, String> getWeChatHead() {
		DefKv kv = defKvMapper.selectByPrimaryKey(WEHCAT_QUERY_KEY);
		if (kv == null)
			throw new SysException("def_kv表中找不到对应的记录，请核实！");
		/* 查询请求来源，SystemKey */
		String key = kv.getV();
		String signature = EncoderUtil.Md5_32(key + timestamp + nonce + SOURCE)
				.toUpperCase();
		Map<String, String> param = new HashMap<String, String>();
		param.put(TIMESTAMP, timestamp);
		param.put(NONCE, nonce);
		param.put(TRADE_SOURCE, SOURCE);
		param.put(SIGNATURE, signature);
		return param;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.hualife.md.common.service.IWeChatGatewayService#getToken()
	 */
	@Override
	public String getToken() {

		Map<String, String> paraMap = getWeChatHead();

		DefKv kv = defKvMapper.selectByPrimaryKey(WEHCAT_QUERY_TOKEN);
		if (kv == null)
			throw new SysException("def_kv表中找不到对应的记录，请核实！");
		/* 查询加密验签KEY */
		String urlValue = kv.getV();
		// 查询接口数据
		String json = HttpUtil.post(urlValue, paraMap, 10000);
		if (json == null || "".equals(json.trim())) {
			logger.error("获取企业号token的返回结果为空！");
			throw new BusinessException("获取企业号token的返回结果为空！");
		} else {
			try {
				WeChatTokenResponseDTO result = (WeChatTokenResponseDTO) JsonUtil
						.SnakeJson2CamelBean(json, WeChatTokenResponseDTO.class);
				if (SUCCESS.equals(result.getResultCode())) {
					if (result.getAccessToken() == null
							|| "".equals(result.getAccessToken().trim())) {
						logger.error("获取企业号token的字段值为空！");
						throw new BusinessException("获取企业号token的字段值为空！");
					} else {
						return result.getAccessToken().trim();
					}
				} else {
					logger.error("获取企业号token失败，原因是：【{}】",result.getResultMsg());
					throw new BusinessException(result.getResultMsg());
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				throw new BusinessException("获取企业号token失败，原因是："
						+ e.getMessage());
			}
		}
	}

}

/*
 * 修改历史 $Log$
 */